package com.openspring.framework.jdbc.sql;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class Update {

	private String tableName;
	private Map<String, String> primaryKeyColumns = new LinkedHashMap<String, String>();
	private Map<String, String> columns = new LinkedHashMap<String, String>();

	public Update setTableName(String tableName) {
		this.tableName = tableName;
		return this;
	}

	public Update addPrimaryKeyColumn(String columnName) {
		addPrimaryKeyColumn(columnName, "?");
		return this;
	}

	public Update addPrimaryKeyColumn(String columnName, String valueExpression) {
		this.primaryKeyColumns.put(columnName, valueExpression);
		return this;
	}

	public Update addColumn(String columnName) {
		return addColumn(columnName, "?");
	}

	public Update addColumn(String columnName, String valueExpression) {
		columns.put(columnName, valueExpression);
		return this;
	}

	public String toUpdateById() {
		StringBuilder sb = new StringBuilder();
		sb.append("UPDATE ").append(tableName).append(" SET ");
		Iterator<Map.Entry<String, String>> iter = columns.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> e = iter.next();
			sb.append(e.getKey()).append(" = ").append(e.getValue());
			if (iter.hasNext()) {
				sb.append(", ");
			}
		}
		if (!primaryKeyColumns.isEmpty()) {
			sb.append(" WHERE ");
		}
		iter = primaryKeyColumns.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> e = iter.next();
			sb.append(e.getKey()).append(" = ").append(e.getValue());
			if (iter.hasNext()) {
				sb.append(" AND ");
			}
		}
		return sb.toString();
	}
}
